package com.homer.android.sdk.command.uart;
import java.net.InetAddress;

import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;

import com.homer.android.sdk.devcie.status.IEspStatusUart;
import com.homer.android.sdk.type.devcie.status.EspStatusUart;
import com.homer.iot.esptouch.base.api.EspBaseApiUtil;
import com.homer.iot.esptouch.tcp.TCPSocketClient;

public class EspCommandUartGetStatusLocal implements IEspCommandUartGetStatusLocal
{
    private final static Logger log = Logger.getLogger(EspCommandUartGetStatusLocal.class);
    static int port = 8800;

	private static TCPSocketClient getTcpSocketClient(String devHost) {
		TCPSocketClient tCPSocketClient = null;
		if (null != devHost) {
			tCPSocketClient = new TCPSocketClient(devHost, port);
			return tCPSocketClient;
		} else {
			return null;
		}
	}
    @Override
    public String getLocalUrl(InetAddress inetAddress)
    {
    	//採用TCP短連接的方式訪問，以下是樂鑫原有的HTTP方式.
        return "http://" + inetAddress.getHostAddress() + "/" + "config?command=switch";
    }
    
    private IEspStatusUart getCurrentUartStatus(InetAddress inetAddress, String deviceBssid)
    {
    	TCPSocketClient tCPSocketClient = getTcpSocketClient(inetAddress
				.getHostAddress());
    	 IEspStatusUart status = new EspStatusUart();
		if (null == tCPSocketClient) {
			tCPSocketClient = getTcpSocketClient(inetAddress.getHostAddress());
			if (null == tCPSocketClient) {
				status.setIsOnline(false);
				return status;
			}
		}
        try
        {
        	boolean isCon = tCPSocketClient.connection();
        	
        	if(isCon){
        		status.setIsLightOn(1);
                status.setIsDefenceOn(1); 
        	}
           
                      
            return status;
        }
        catch (Exception e)
        {
        	status.setIsOnline(false);
            e.printStackTrace();
        }
        finally {
			tCPSocketClient.close();
		}
        return status;
    }
    
    @Override
    public IEspStatusUart doCommandUartGetStatusLocal(InetAddress inetAddress)
    {
        IEspStatusUart result = getCurrentUartStatus(inetAddress, null);
        log.debug(Thread.currentThread().toString() + "##doCommandUartGetStatusLocal(inetAddress=[" + inetAddress
            + "]): " + result);
        return result;
    }
    
    @Override
    public IEspStatusUart doCommandUartGetStatusLocal(InetAddress inetAddress, String deviceBssid)
    {
        IEspStatusUart result = getCurrentUartStatus(inetAddress, deviceBssid);
        log.debug(Thread.currentThread().toString() + "##doCommandUartGetStatusLocal(inetAddress=[" + inetAddress
            + "],deviceBssid=[" + deviceBssid + "]");
        return result;
    }
    
}
